scala类转换为json | 您所在的位置:网站首页 › scala some转string › scala类转换为json |
scala类转换为json
一,依赖二,java实例三,scala实例四,原因
使用fastjson将java 实体类转换为json很方便,但是直接用在普通的Scala实体类上生成的json是空的"{}",需要使用scala.beans.BeanProperty注解修饰一下scala类字段。
一,依赖
8
8
1.2.54
com.alibaba
fastjson
${fastjson.version}
二,java实例
public class JavaUser {
private String userName;
private String userSex;
private int id;
public JavaUser(String userName,String userSex,int id){
this.userName=userName;
this.userSex=userSex;
this.id=id;
}
public String getUserName() {
return userName;
}
public String getUserSex() {
return userSex;
}
}
import com.alibaba.fastjson.*;
public class JavaTest {
public static void main(String[] args) {
System.out.println(JSON.toJSONString(new JavaUser("zhangsan","man",1)));
}
}
Scala中代码 var类型字段=private变量+getter+setter; val类型字段=private变量+getter; 但是命名方式与java不同,getter为字段名,setter为**字段名_()**的形式,与fastjson要求的命名方式不一致。BeanProperty则能提供java风格的getter和setter。 package scala.beans /** When attached to a field, this annotation adds a setter and a getter * method following the Java Bean convention. For example: * {{{ * @BeanProperty * var status = "" * }}} * adds the following methods to the class: * {{{ * def setStatus(s: String) { this.status = s } * def getStatus: String = this.status * }}} * For fields of type `Boolean`, if you need a getter named `isStatus`, * use the `scala.beans.BooleanBeanProperty` annotation instead. */ @scala.annotation.meta.field class BeanProperty extends scala.annotation.StaticAnnotation |
CopyRight 2018-2019 实验室设备网 版权所有 |